<?php

namespace App\Http\Middleware;

use App\Models\Wxuser;
use Closure;
use Illuminate\Support\Facades\Cache;

class CheckToken
{

    public function handle($request, Closure $next)
    {
        $token = $request->header('token');
        if(in_array($request->path(),config('skip')))
            return $next($request);
        if(!empty($token)&&count($token)>0){
            $user = Wxuser::where('token',$token)->first();
            if($user){
                if(Cache::has($user->openid)){
                    $authToken = Cache::get($user->openid);
                    if($authToken==$token){
                        return $next($request);
                    }else{
                        return response()->json(['status'=>401,'info'=>'token失效']);
                    }
                }else{
                    return response()->json(['status'=>401,'info'=>'token过期']);
                }
            }else{
                return response()->json(['status'=>401,'info'=>'找不到用户']);
            }
        }else{
            return response()->json(['status'=>401,'info'=>'token为空']);
        }
    }
}